/**
 * Copyright (c) 2011 Alexander De Leon Battista
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package es.upm.oeg.presto.rewrite.impl;

import org.weborganic.furi.Parameters;
import org.weborganic.furi.URIParameters;
import org.weborganic.furi.URIPattern;
import org.weborganic.furi.URIResolveResult;
import org.weborganic.furi.URIResolver;
import org.weborganic.furi.URITemplate;

import es.upm.oeg.presto.rewrite.URISpaceMapping;

/**
 * @author Alexander De Leon
 */
public class URISpaceMappingImpl implements URISpaceMapping {

	private final URITemplate source;
	private final URITemplate target;

	public URISpaceMappingImpl(String sourceTemplate, String targetTemplate) {
		super();
		source = new URITemplate(sourceTemplate);
		target = new URITemplate(targetTemplate);
	}

	@Override
	public URITemplate source() {
		return source;
	}

	@Override
	public URITemplate target() {
		return target;
	}

	@Override
	public String rewrite(String uri) {
		URIResolver resolver = new URIResolver(uri);
		URIResolveResult result = resolver.resolve(new URIPattern(source));
		Parameters params = getParameters(result);
		return target.expand(params);
	}

	private Parameters getParameters(URIResolveResult result) {
		URIParameters parameters = new URIParameters();
		for (String name : result.names()) {
			parameters.set(name, result.get(name).toString());
		}
		return parameters;
	}
}
